package ch.yoursource.StartPageBuilder;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Vector;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;

/**
 * Provides gui and stuff to create javascript powered hotkey html pages
 * @author mbk
 */
public class SPB {
    private static SPB instance;
    final DefaultTableModel model = new DefaultTableModel(columnNames(),0);
    private JFrame frmSPB = new JFrame();
    private JPanel panSPB = new JPanel();
    private JTable table = new JTable(model);
    private JButton btnAdd = new JButton("Add");
    private JButton btnRem = new JButton("Remove selected entries");
    private JButton btnWrite = new JButton("Save & use");
    private JButton btnLoad = new JButton("Load");
    private String[][] list = new String[0][columnNames().length];
    
    //TODO: Javadoc
    /**
     * 
     */
    public SPB() {        
        SPB.instance = this;
    }
    //TODO: Javadoc
    public void launchGUI() {
        //ActionListeners
        btnAdd.addActionListener( new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                String[] rowData = new String[3];
                String hotkey = prompt("Hotkey");
                String url = prompt("URL");
                int newTab = confirm("Open website in new tab?");
                rowData[0] = hotkey;
                rowData[1] = url;
                rowData[2] = String.valueOf(newTab);
                list = addEntry(hotkey,url,newTab,list);
                int numColumns = model.getColumnCount();
                Vector<String> newDatas = createDataVector(numColumns,rowData);
                model.addRow(newDatas);
            }
        });
        btnRem.addActionListener( new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                int selected[] = table.getSelectedRows();
                int numSelected = selected.length;
                list = removeSelectedEntries(list, selected);
                for(int i=numSelected-1;i>=0;i--) {                    
                    model.removeRow(selected[i]);
                }
            }
        });
        btnLoad.addActionListener( new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                instance.loadSettings();
                SPB.fillTable();
            }
        });
        btnWrite.addActionListener( new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                PageWriter.write(instance.list);
            }
        });

        panSPB.add(new JScrollPane(table), BorderLayout.CENTER);
        panSPB.add(btnAdd); 
        panSPB.add(btnRem);
        panSPB.add(btnWrite);
        panSPB.add(btnLoad);
        
        frmSPB.setTitle("Startpage generator");       
        frmSPB.getContentPane().add(panSPB);
        frmSPB.pack();
        frmSPB.setSize(490, 500);
        frmSPB.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frmSPB.setVisible(true);
    }
    
    
    
    
    //TODO: Javadoc
    private static String[] columnNames() {
        String[] cN = new String[3];
        cN[0] = "Hotkey";
        cN[1] = "URL";
        cN[2] = "new Tab";
        return cN;
    }
    //TODO: Javadoc
    private void loadSettings() {
        instance.list = Loader.loadSettings();
    }
    //TODO: Javadoc
    private static String[][] addEntry(String hotkey, String url, int newTab, String[][] list){
        int newListLength = list.length+1;
        String[][] tmpArr = new String[newListLength][3];
        for(int i=0;i<list.length;i++) {
            tmpArr[i]=list[i];
        }        
        tmpArr[newListLength-1][0] = hotkey;
        tmpArr[newListLength-1][1] = url;
        tmpArr[newListLength-1][2] = String.valueOf(newTab);
        return tmpArr;
    }
    //TODO: Javadoc
    private static String[][] removeSelectedEntries(String[][] list,int[] indices) {
        String[][] tmpArr = new String[list.length-indices.length][columnNames().length];
        
        for(int i=0,j=0;i<list.length;i++) {
            if(!inArray(indices,i)) {
                tmpArr[j] = list[i];
                j++;
            } else {
                continue;
            }
        }
        return tmpArr;
    }        
    /**
     * Checks if value is in array
     * @param array - array that might contain value
     * @param value - value that is in array or not
     * @return true or false
     */
    private static boolean inArray(int[] array, int value) {
        for(int i=0;i<array.length;i++){
            if(array[i] == value) {
                return true;
            }
        }
        return false;
    }    
    /**
     * Prompts for input and returns result 
     * @param text - text that will be shown in input dialog
     * @return entered text
     */
    private static String prompt(String text) {
        String tmp = javax.swing.JOptionPane.showInputDialog(instance.frmSPB,text);
        return tmp;
    }
    /**
     * Prompts for yes or no and returns result
     * @param text - text that will be shown in confirm dialog
     * @return true or false  
     */
    private static int confirm(String text) {
        int tmp = javax.swing.JOptionPane.showConfirmDialog(instance.frmSPB, text);
        if(tmp == javax.swing.JOptionPane.YES_OPTION) {
            return 1;
        } else {
            return 0;
        }
    }
    //TODO: Javadoc
    private static Vector<String> createDataVector( int numColumns, String[] rowData ){
        Vector<String> vector = new Vector<String>( numColumns );
        for( int i = 0; i < numColumns; i++ )
            vector.add( rowData[i] );
        return vector;
    }
    //TODO: Javadoc
    private static void fillTable() {
        for(int i=0;i<instance.model.getRowCount();i++) {
            instance.model.removeRow(i);
        }
        for(int i=0;i<instance.list.length;i++) {
            instance.model.addRow(createDataVector(instance.list[i].length,instance.list[i]));
        }
    }
    
    
    
    
    /**
     * 
     * @return settings string for html file
     */
    public static String getSettings() {
        StringBuilder cuts = new StringBuilder();
        for(int i=0;i<instance.list.length;i++) {
            for(int j=0;j<3;j++) {
                cuts.append(instance.list[i][j]);
                if(j+1!=3) {
                    cuts.append(";");
                }
            }
            if(i+1!=instance.list.length) {
                cuts.append("#ENTRY#");
            }
        }
        return cuts.toString();
    }
    //TODO: Javadoc
    public static String getTitle() {
        return ".";
    }
    //TODO: Javadoc
    public static String getShortcuts() {
        StringBuilder cuts = new StringBuilder();
        for(int i=0;i<instance.list.length;i++) {
            if(instance.list[i][2].equals("0")) {
                cuts.append("shortcut.add(\""+instance.list[i][0]+"\", function() { window.location = \""+instance.list[i][1]+"\";});");
            } else {
                cuts.append("shortcut.add(\""+instance.list[i][0]+"\", function() { window.open(\""+instance.list[i][1]+"\");});");
            }
        }
        return cuts.toString();
    }
}